﻿using Anonym.MVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using Microsoft.Extensions.DependencyInjection;
using Anonym.Data;
using Anonym.Data.Entities;
using System.Threading;
using Anonym.Service;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using Anonym.Common.MyAttribute;
using Anonym.Models.Common;
using Anonym.Common;
using Anonym.Models.Objects;

namespace Anonym.MVC.Controllers
{
    public class HomeController : Controller
    {
        private SqlSugarClient Db { get; set; }
        private readonly ILogger<HomeController> _logger;
        private User user { get; set; }
        //private IHttpContextAccessor _accessor;
        private Temp temp { get; set; } = new Temp();
        private CmsBasicsInfo CmsBasicsInfo { get; set; }
        private IServiceProvider ServiceProvider { get; set; }

        public HomeController(ILogger<HomeController> logger, IServiceProvider p)
        {
            //, IHttpContextAccessor accessor
            //_accessor = accessor;
            var s = p.GetService<Temp>();
            //var a0 = _accessor.HttpContext.Items["bbb"];
            //var aaa1 = p.GetService<Log_Interface>();
            //var aa2 = this.ControllerContext.RouteData.Values["aaa"];
            //var aa3 = actiona .ActionArguments["loginInfo"];
            //var p = service.BuildServiceProvider();
            var dbConn = p.GetService<IConfiguration>().GetSection("DbConnect").Get<string>();
            Db = p.GetService<DbProvider>().GetInstance();
            _logger = logger;
            user = p.GetService<User>();
            temp = p.GetService<Temp>();
            //abc.id = 55; abc.name = "yyyyyy";
            ServiceProvider = p;
            CmsBasicsInfo = ServiceProvider.GetService<CmsBasicsInfo>();
        }

        [NoToken, CmsNoMenuPage]
        public IActionResult Index()
        {
            //var id = temp.id;
            //var name = temp.name;
            var id = user.Test;
            var a0 = HttpContext.Items["bbb"];
            var sss = HttpContext.Request.BodyReader;
            #region EF测试
            //var db = new Log_InterfaceContext();
            //Log_Interface obj = new Log_Interface();
            //obj.ControlName = "ControlName";
            //obj.ActionName = "ActionName";
            //obj.StartTime = DateTime.Now;
            //db.Add(obj);

            //L_Bank bank = new L_Bank();
            //bank.Name = "11111";
            //bank.Rebate = 15;
            //bank.Remark = "备注";
            //db.Add(bank);

            //var list1 = db.Log_Interface.FromSqlRaw("select top 3 * from Log_Interface").ToList();
            //var i = db.Database.ExecuteSqlRaw("select * from L_Bank");
            //var list2 = db.Set<Test>().FromSqlRaw("select * from L_Bank").ToList();

            ////Log_Interface delObj = db.Log_Interface.Where(w => w.Id == 2).FirstOrDefault();
            ////db.Remove(delObj);

            //db.SaveChanges();
            ////db.Entry(obj);

            //var list = db.Log_Interface.ToList();
            #endregion

            #region SqlSugar测试
            Log_Interface sObj = new Log_Interface();
            sObj.ControlName = "ControlName";
            sObj.ActionName = "ActionName";
            sObj.StartTime = DateTime.Now;
            //long id = Db.Insertable(sObj).ExecuteReturnBigIdentity();

            //List<Log_Interface> liList = Db.Queryable<Log_Interface>().ToList();
            //Log_Interface dtId = Db.Queryable<Log_Interface>().InSingle(id);
            //var liList2 = Db.Queryable<Log_Interface>().Where(w => w.ActionName.Contains("1")).ToList();

            //sObj.Id = id;
            //sObj.Link = @"www.baidu.com";
            //sObj.ActionName = "修改后";
            //sObj.RequestIp = "0.0.0.0";
            //Db.Updateable(sObj).ExecuteCommand();
            #endregion

            ViewBag.cc = "ding";
            ViewData["hh"] = "rinima";

            return View();
        }

        [NoToken, CmsNoMenuPage]
        public async Task<string> GetTestVal()
        {
            long id = CmsBasicsInfo.ID;
            Random r = new Random();
            //User u = ServiceProvider.GetService<User>();
            return await Task<string>.Run(() =>
            {
                Thread.Sleep(2000);
                //return "GetString的返回值";
                return user.Get(r.Next());
            });
        }

        [NoToken, CmsNoMenuPage]
        public IActionResult Privacy(int val)
        {
            try
            {
                var id = temp.id;
                var name = temp.name;
                var i = 1 / val;
            }
            catch (Exception ex)
            {

            }
            return View();
        }

        //[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        //public IActionResult Error()
        //{
        //    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        //}

        [NoToken, CmsNoMenuPage]
        public IActionResult Error()
        {
            Error e = new Error();
            if (!string.IsNullOrEmpty(HttpContext.Session.GetString("Error")))
                e = HttpContext.Session.GetObject<Error>("Error");
            else
            {
                e.Msg = "您还未登录系统，或长时间未操作系统，请重新登录！";
                e.Code = 8001;
                e.Url1 = "/home/login";
                e.UrlStr = "返回登录页面";
                e.Target = "_top";
            }
            return View(e);
        }

        public object Test1([FromBody] Value1 val)
        {
            var id = temp.id;
            var name = temp.name;
            return JsonConvert.SerializeObject(val);
        }

        [NoToken, CmsNoMenuPage]
        public IActionResult Login(CommonRequest request)
        {
            //,[FromBody]Value1 val
            //ViewBag.val = val.ToJson();
            ViewBag.req = request.RequestContent;
            return View();
        }

        [NoToken]
        public IActionResult TestMenu()
        {

            return View();
        }
    }

    public class Value1
    {
        public int Id { get; set; } = 0;
        public string Name { get; set; } = string.Empty;
        public string Content { get; set; } = string.Empty;
    }
}
